package com.ccsoft.multithread.test;

/**
 * @author chanchaw
 * @create 2022-08-05 13:56
 * 使用3个线程分别打印：a,b,c。要求交替执行，累计打印5组
 * 本案例演示 synchronized wait notify 方式实现
 */
public class No301AlternateWaitNotify {
    public static void main(String[] args) {
        WaitNotify waitNotify = new WaitNotify(5, 0);
        Thread t1 = new Thread(()->{
            waitNotify.doWork("a",0,1);
        },"t1");

        Thread t2 = new Thread(()->{
            waitNotify.doWork("b",1,2);
        },"t2");

        Thread t3 = new Thread(()->{
            waitNotify.doWork("c\n",2,0);
        },"t3");


        t2.start();
        t3.start();
        t1.start();
    }
}

class WaitNotify {
    private int loopNumber = 1;
    private int allowedFlag = 0;

    public WaitNotify(int loopNumber, int allowedFlag) {
        this.loopNumber = loopNumber;
        this.allowedFlag = allowedFlag;
    }

    public void doWork(String printString,int currentFlag,int nextFlag){
        for (int i = 0; i < loopNumber; i++) {
            synchronized (this){
                while(allowedFlag != currentFlag){
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.print(printString);
                allowedFlag = nextFlag;
                notifyAll();
            }
        }
    }
}
